<?php

namespace Home\Controller;

// use Think\Controller;
// use Vendor\httpful-2.phar;
import ( "Home.Library.QueryList.QueryList" );
class SsDealpage {
	
	// 经纬度， 是否在数据库里
	static $addresspos = array ();
	
	// 默认配置
	public function load() {
		
		// 载入已经缓存过的地址
		$this->loadaddresspos ();
		
		// $this->saveaddresspos();
		
		// 遍历pc目录下所有缓存文件
		$path = C ( 'SS_CACHEPATH' );
		$uri=C('XBB_URI');
		$mydir = dir ( $path );
		
		while ( $file = $mydir->read () ) {
			
			$filename = $path . $file;
			// echo $filename . "</br>";
			
			if (! is_dir ( "$filename" )) {
				
				// echo "<li>$file</li>\n";
				
				$url = $uri . $path . "/" . $file;
				
				if (! $this->listpages ( $url )) {
					break;
				}
				// 当前数据处理过了， 删除缓存页面
				// unlink ( $filename );
				
				
			}
		}
		
		$mydir->close ();
	}
	
	// 载入数据库地址
	function loadaddresspos() {
		$addpos = D ( 'addresspos' );
		
		$resdata = $addpos->select ();
		// var_dump($resdata);
		$num = count ( SsDealpage::$addresspos );
		for($i = 0; $i < $num; $i ++) {
			
			var_dump ( $resdata );
			
			$key = $resdata [$i] ["address"];
			$value = array (
					$resdata [$i] ["lat"],
					$resdata [$i] ["lng"],
					1 
			);
			
			SsDealpage::$addresspos [$key] = $value;
		}
		
		var_dump ( SsDealpage::$addresspos );
	}
	
	// 写入数据库地址
	function saveaddresspos() {
		$addpos = D ( 'addresspos' );
		
		echo "</br>---------";
		
		// var_dump($resdata);
		$num = count ( SsDealpage::$addresspos );
		
		foreach ( SsDealpage::$addresspos as $key => $value ) {
			
			if ($value [2] == 0) {
				try {
					$data {"address"} = $key;
					$data {"lat"} = $value [0];
					$data {"lng"} = $value [1];
					$addpos->add ( $data );
					$value [2] = 1;
				} catch ( \Think\Exception $e ) {
					
					echo "添加坐标缓存失败" . $e->getMessage () . "</br>";
				}
			}
			
			var_dump ( $value );
			echo "</br>---------";
		}
	}
	function listpages($url) {
		$orders = array ();
		$this->dealPage ( $url, $orders );
		
		// var_dump($orders);
		// 获取订单的经纬度信息
		if (! $this->getOrderPos ( $orders )) {
			echo "今日不宜处理数据，暂停";
			return false;
		}
		
		$num = count ( $orders );
		$ex = false;
		
		$x = 0;
		for($x = 0; $x < $num; $x = $x + 1) {
			$order = $orders [$x];
			
			$dborder = D ( 'order' );
			$order->str2time ();
			
			try {
				
				if ($order->lat == null) {
					$order->lat = 0;
					$order->lng = 0;
				}
				
				$map["id"]=$order->id;
				$resdata=$dborder->where($map)->select();
				
// 				  var_dump($resdata);
							
			// 有update的情况
			   if($resdata)
			   {
			   	
			   	
			   }else 
			   {
			   	$res = $dborder->data ( $order )->add ();
			   	
			   }
				
				
			} catch ( \Think\Exception $e ) {
				
				echo "添加数据失败" . $e->getMessage () . "</br>";
				// return false;
				$ex = true; // 发生异常了
			}
		}
		
		return true;
	}
	
	/**
	 * 补全 order中的位置坐标
	 *
	 * @param unknown $orders        	
	 */
	public function getOrderPos($orders) {
		$ak = C ( "ak" );
		
		// 根据add 详细信息， 获取百度地图坐标点， 在 地图上打出来
		$num = count ( $orders );
		// echo $num . "test</br>";
// 		  echo var_dump($orders);
		
		$x = 0;
		for($x = 0; $x < $num; $x = $x + 1) {
			$order = $orders [$x];
			
			// echo "</br>order add</br>";
			if ($this->dealposinfoCache ( $order )) {
				// 命中cache坐标
				echo "命中cache坐标</br>";
				continue;
			}
			
			if(!$this->dealposinfo ( $order ))
			{
// 				return false;
			}
			
			
		}
		
		return true;
	}
	function dealposinfoCache(&$order) {
		$addback = $this->getAdd ( $order->address );
		$addback2 = $this->getAddKeyword ( $order->address, $order->adddetail );
		$addback3 = $this->getAddSymbol ( $order->address );
		
		$addarray = array (
				$addback,
				$addback2,
				$addback3 
		);
		
		for($i = 0; $i < 3; $i ++) {
			$key = $addarray [$i];
			$value = SsDealpage::$addresspos [$key];
			if ($value) {
				$order->address = $key;
				$order->lat = $value [0];
				$order->lng = $value [1];
				
				echo "<br/>cache add=" . $key . " lat =" . $order->lat . "   lng=" . $order->lng . "</br>";
				return true;
			}
		}
		
		return false;
	}
	function dealposinfo(&$order) {
		$addback = $this->getAddKeyword ( $order->address );
		if($addback)
		{
			$res = $this->getMapPos ( $addback );
			
		}
		
		echo "<br/>dealposinfo  addback=" . $addback . "  </br> address=" . $order->address;
		echo "<br/>adddetail=" . $order->adddetail . "lat=" . $order->lat . "</br>";
		
		echo var_dump ( $res );
		
		if ($res) {
			
			if (stripos ( $res, "\"status\":302" ) > 0) {
				echo "<br/>百度地图api超配额 不可用</br>";
				
				return false;
			}
			
			// 找出第一个结果的坐标
			$this->getLatLngKey ( $res,$addback, $order->lat, $order->lng );
		} else {
			echo "<br/>百度地图api不可用</br>";
			return false;
		}
		
		if ($order->lat == 0 || $order->lat == null) {
			
			echo "<br/>11</br>";
			$addback = $this->getAddSymbol ( $order->address, $order->adddetail );
			
			$res = $this->getMapPos ( $addback );
			// 找出第一个结果的坐标
			$this->getLatLngKey ( $res,$addback, $order->lat, $order->lng );
			
			if ($order->lat == 0) {
				$addback = $this->getAdd( $order->address );
				
				$res = $this->getMapPos ( $addback );
				// 找出第一个结果的坐标
				$this->getLatLngKey ( $res,$addback, $order->lat, $order->lng );
			}
		}
		
		if ($order->lat != 0||strlen($order->lat)!=0) {
			echo "<br/>22</br>";
			$order->address = $addback;
			$value = array (
					$order->lat,
					$order->lng,
					0 
			);
			
			SsDealpage::$addresspos [$order->address] = $value;
			
			$this->saveaddresspos ();
		} else {
			
			$order->lat = 0;
			$order->lng = 0;
		}
		
		echo "<br/>final lat =" . $order->lat . "   lng=" . $order->lng . "</br>";
	}
	function getAddKeyword($add, $adddetail) {
		
// 		echo "<br/>getAddKeyword add =" . $add. "   </br>";
		
		$key_array = array (
				"店",
				"区",
				"门",
				"口",
				"北京",
				"厅",
				"行",
				"所",
				"院",
				"处",
				"东南",
				"部",
				"中心",
				"辅路",
				"北",
				"东" 
		);
		
		$num = count ( $key_array );
		$pos = - 1;
		for($i = 0; $i < $num; $i ++) {
			$pos = stripos ( $add, $key_array [i] );
			
			if ($pos > 0) {
				break;
			}
		}
		
		if($pos==-1)
		{
			return null;
		}		
		
		$strAdd = "(" . $add . ")";
		
// 		echo "<br/>  $strAdd =" . $strAdd. "   </br>";
		
		$pos2 = strpos ( $adddetail, $strAdd );
		if ($pos2 > 0) {
			$address = substr ( $adddetail, 0, $pos2 ) . $strAdd;
			return $address;
		}
		
		//address=和颐酒店（天坛店）（北京市东城区北京安乐林路10号22号楼(安乐林路与景泰路交叉口，京坛医院向南100米或赵公口桥向北500米)）
		
		$pos3= stripos($add,"）（");
	    if($pos3>0)
	    {
	    	$address = substr ( $adddetail, 0, $pos3+3 ) ;
	    	
// 	    	echo "<br/>  pos3=".$pos3." strAdd =" . $address. "   </br>";
	    	return $address;
	    	
	    }
	
		
	 
	}
	function getAddSymbol($address) {
		$dot = ".";
		
		$len = strlen ( $dot );
		
		$pos = strpos ( $address, $dot );
		if ($pos > 0) {
			$address = substr ( $address, 0, $pos ) . substr ( $address, $pos + $len );
			
			return $address;
		}
		
		$dot = "--";
		
		$len = strlen ( $dot );
		
		// echo $len;
		
		$pos = strpos ( $address, $dot );
		$pos2 = strpos ( $address, "(" );
		if ($pos > 0) {
			$address = substr ( $address, 0, $pos2 );
			
			return $address;
		}
		
		$pos = strpos ( $address, "-" );
		
		if ($pos > 0) {
			$address = substr ( $address, 0, $pos );
			
			return $address;
		}
	}
	
	// 获取缩略地址的默认逻辑
	function getAdd($add) {
		$pos = stripos ( $add, "(" );
		
		$pos2 = stripos ( $add, ")" );
		
		$pos3 = stripos ( $add, "（" );
		
		// echo "</br>pos=" . $pos . " " . $pos2." ".$pos3;
		
		if ($pos3 < $pos) {
			$app = substr ( $add, 0, $pos3 );
		} else {
			
			if ($pos2 > $pos) { // 有两套括号
				$app = substr ( $add, $pos + 1, $pos2 - $pos - 1 );
			} else {
				
				$app = substr ( $add, 0, $pos3 );
			}
		}
		
		/* */
		
		return $app;
		
		// echo "</br>app=" . $app;
		
		// if (strlen ( $addback ) > 0) {
		// return $app;
		// } else {
		// return $add;
		// }
	}
	function getMapPos($pos) {
		
		
		return NULL;
		
		$ak = C ( "ak" ); // "CODkPQCSklf3jGmVpdOZEi6g";
		                  // $pos="天雅大厦";
		$url = "http://api.map.baidu.com/place/v2/suggestion?query=" . $pos . "&region=北京市&output=json&ak=" . $ak;
		
		// echo $url;
		$res = file_get_contents ( $url );
		
		return $res;
	}
// 	function getLatLng($res, &$lat, &$lng) {
// 		$de_json = json_decode ( $res, true );
// 		$count_json = count ( $de_json );
		
// 		echo count ( $de_json ["result"] );
// 		echo "</br>";
		
// 		$numres = count ( count ( $de_json ["result"] ) );
// 		// echo var_dump ( $de_json ["result"] [0] ["location"] ["lat"] );
// 		if ($count_json > 0) {
			
// 			for($i = 0; $i < $numres; $i ++) {
// 			}
			
// 			$location = $de_json ["result"] [0] ["location"];
// 			$lat = $location ["lat"];
// 			$lng = $location ["lng"];
			
// 			// if (strlen ( $lat ) == 0) {
			
// 			// if ($count_json > 1) {
// 			// $location = $de_json ["result"] [1] ["location"];
// 			// $lat = $location ["lat"];
// 			// $lng = $location ["lng"];
// 			// }
			
// 			// if (strlen ( $lat ) == 0) {
// 			// if ($count_json > 2) {
// 			// $location = $de_json ["result"] [2] ["location"];
// 			// $lat = $location ["lat"];
// 			// $lng = $location ["lng"];
// 			// }
// 			// }
// 			// }
			
// 			// echo "</br>lat=" . $lat . " lng=" . $lng;
// 		}
// 	}
	function getLatLngKey($res, $key, &$lat, &$lng) {
		$de_json = json_decode ( $res, true );
		$count_json = count ( $de_json );
		
// 		echo count ( $de_json ["result"] );
// 		echo "</br>";
		
		$numres = count ( count ( $de_json ["result"] ) );
		// echo var_dump ( $de_json ["result"] [0] ["location"] ["lat"] );
		if ($count_json > 0) {
			
			for($i = 0; $i < $numres; $i ++) {
				
				$name = $de_json ["result"] [$i] ["name"];
				if ($name == $key) {
					$location = $de_json ["result"] [$i] ["location"];
					$lat = $location ["lat"];
					$lng = $location ["lng"];
					return;
				}
			}
			
			$location = $de_json ["result"] [0] ["location"];
			$lat = $location ["lat"];
			$lng = $location ["lng"];
			
			// if (strlen ( $lat ) == 0) {
			
			// if ($count_json > 1) {
			// $location = $de_json ["result"] [1] ["location"];
			// $lat = $location ["lat"];
			// $lng = $location ["lng"];
			// }
			
			// if (strlen ( $lat ) == 0) {
			// if ($count_json > 2) {
			// $location = $de_json ["result"] [2] ["location"];
			// $lat = $location ["lat"];
			// $lng = $location ["lng"];
			// }
			// }
			// }
			
			// echo "</br>lat=" . $lat . " lng=" . $lng;
		}
	}
	function dealPage($url, &$orders) {
		$reg = array (
				
				'row' => array (
						
						'td',
						
						'text' 
				) 
		);
		
		// $reg = array( 'info'=>array('.taskInfo','text'));
		
		$hj = new \QueryList ( $url, $reg );
		
		$rowarray = $hj->getJSON ();
		
		$rownum = count ( $rowarray );
		
		$rowline = json_decode ( $rowarray );
		
		// echo var_dump( $rowline);
		
		// echo "var_dump(line0)</br>";
		
		// echo var_dump( $rowline[1]);
		
		// echo $rowline;
		
		$rownum = count ( $rowline );
		
		// echo "</br>rownum=" . $rownum;
		
		for($x = 0; $x < $rownum; $x = $x + 6) {
			
			// echo "</br> " . $x . " </br>";
			
			$order = new SSOrder (); // D ( 'order' );
			
			$lineData = $rowline [$x + 0];
			
			// echo var_dump ( $lineData->row );
			
			$this->getOrdertime ( $lineData->row, $order );
			
			// echo "</br>";
			
			$lineData = $rowline [$x + 1];
			
			// echo var_dump ( $lineData->row );
			
			$this->getUserinfo ( $lineData->row, $order );
			
			// echo "</br>";
			
			$lineData = $rowline [$x + 3];
			
			$this->getSSUserinfo ( $lineData->row, $order );
			
			// echo var_dump ( $lineData->row );
			
			// echo "</br>";
			
			// echo var_dump ( $order );
			if ($order->status == 1) {
				array_push ( $orders, $order );
				// $pos = stripos ( $order->endtime, "70" );
				// if ($pos > 0) {
				// echo $pos . " " . $order->endtime . "</br>";
				// echo var_dump ( $order );
				// }
				// echo var_dump ( $order );
				
				// echo "</br></br></br>";
			}
		}
	}
	function getOrdertime($rawData, &$order) 

	{
		/**
		 * <td>DH1010102971681<br>
		 * 下单时间：15-12-13 23:03<br>
		 *
		 *
		 * <br>取件时间：15-12-13 23:19
		 * <br>收件时间：15-12-14 00:07</br>
		 * <b style="color: red">夜间单</b>
		 * </td>
		 * <td>
		 * biu`biu，18610721057<br/>
		 * 剧空间(新街口)（北京市西城区新街口北大街74号8-12幢剧空间餐厅二楼(万特珠宝东北侧)） <br>
		 * <!--收件人信息-->
		 *
		 * <div class="taskInfo" data-task="DH10101029716811" data-order="DH1010102971681" data-sta="60" data-sta-desc="已完成" data-type="1">
		 * (1),黄容 先生,18611676929
		 * <span class="badge badge-green">已完成</span>
		 * <br/>
		 * 劲松六区601号楼（北京市朝阳区劲松六区601号楼） 劲松六区601号楼 4门603
		 * </div>
		 *
		 *
		 * 备注：保温<br/>
		 *
		 * 物品名称：食物
		 * </td>
		 * <td>
		 * 34元/9.9公里/5千克<br>
		 * 优惠抵扣：4元<br/>
		 *
		 * 余额支付：30元<br/>
		 *
		 *
		 *
		 *
		 * </td>
		 */
		
		// DH1010050937461 下单时间：15-10-06 14:52
		// string(80) "DH1010050933887 下单时间：15-10-06 14:46取件时间：15-10-06 14:52"
		
		// 先用空格切分下
		// echo "</br>";
		$kerwords = preg_split ( "/[\s,]+/", $rawData );
		
		// echo var_dump ( $kerwords );
		
		// echo "</br>";
		
		$order->id = $kerwords [0];
		
		$keywordnum = count ( $kerwords );
		
		if ($keywordnum > 7) {
			echo "keynum=$keywordnum</br>";
		}
		
		if ($keywordnum == 6 || $keywordnum == 7) {
			// array(6) { [0]=> string(15) "DH1010050902494" [1]=> string(23) "下单时间：15-10-06"
			// [2]=> string(28) "13:56取件时间：15-10-06" [3]=> string(5) "14:00" [4]=> string(23) "收件时间：15-10-06" [5]=> string(5) "14:29" }
			
			$pos = strlen ( $kerwords [1] ) - 8;
			
			$order->ordertime = substr ( $kerwords [1], $pos ) . " " . substr ( $kerwords [2], 0, 5 );
			
			$pos = strlen ( $kerwords [2] ) - 8;
			
			$order->starttime = substr ( $kerwords [2], $pos ) . " " . $kerwords [3];
			
			$pos = strlen ( $kerwords [4] ) - 8;
			$order->endtime = substr ( $kerwords [4], $pos ) . " " . $kerwords [5];
		} 

		else if ($keywordnum == 4) 

		{
			// array(4) { [0]=> string(15) "DH1010050933887" [1]=> string(23) "下单时间：15-10-06" [2]=> string(28) "14:46取件时间：15-10-06" [3]=> string(5) "14:52" }
			
			$pos = strlen ( $kerwords [1] ) - 8;
			
			$order->ordertime = substr ( $kerwords [1], $pos ) . " " . substr ( $kerwords [2], 0, 5 );
			
			// echo $order->ordertime;
			// echo "</br>";
			
			$pos = strlen ( $kerwords [2] ) - 8;
			
			$order->starttime = substr ( $kerwords [2], $pos ) . " " . $kerwords [3];
			// echo $order->starttime;
			// echo "</br>";
		} else if ($keywordnum == 3) {
			
			// array(3) { [0]=> string(15) "DH1010050937461" [1]=> string(23) "下单时间：15-10-06" [2]=> string(5) "14:52" }
			$pos = strlen ( $kerwords [1] ) - 8;
			
			$order->ordertime = substr ( $kerwords [1], $pos ) . " " . $kerwords [2];
			
			// echo $order->ordertime;
		}
	}

	/**
	 * @param $rawData
	 * @param $order
     */
	function getUserinfo($rawData, &$order)

	{
		
		/**
		 * <td>
		 * biu`biu，18610721057<br/>
		 * 剧空间(新街口)（北京市西城区新街口北大街74号8-12幢剧空间餐厅二楼(万特珠宝东北侧)） <br>
		 * <!--收件人信息-->
		 *
		 * <div class="taskInfo" data-task="DH10101029419161" data-order="DH1010102941916" data-sta="60" data-sta-desc="已完成" data-type="1">
		 * (1),梁治国,,18910610281
		 * <span class="badge badge-green">已完成</span>
		 * <br/>
		 * 上地雅美科技园（北京市海淀区安宁庄西三条） 海淀区 安宁庄西三条雅美科技园北侧You 国际青年公寓259
		 * </div>
		 *
		 *
		 * 备注：保温<br/>
		 *
		 * 物品名称：食物
		 * </td>
		 */
		
		// echo "</br>keyword=</br>";
		$kerwords = preg_split ( "/[\s,]+/", $rawData );
		

		
//		$keywordnum = count ( $kerwords );
		$offset =0;

		
		if (strlen ( $kerwords [5] ) == 11) {
			$offset = - 1;
		} else if (strlen ( $kerwords [4] ) == 11) {
			$offset = - 2;
		}
		
		// echo "</br>---";
		
		// echo var_dump ($kerwords[0]);
		$order->startadd = $kerwords [1];
		
		$order->name = $kerwords [3];
		$order->sex = $kerwords [4];
		if ($order->sex == '先生') {
			$order->sex = 1;
		} else {
			$order->sex = 0;
		}
		
		$order->mobile = $kerwords [6 + $offset];
		$order->district = "";

		$offsetadd = 0;

		
		if (strlen ( $kerwords [7 + $offset] ) != 9) {

			$offsetadd = -1;
		} else {
			$order->status = $kerwords [7 + $offset];
		}
		
		if ($order->status == '已完成') {
			$order->status = 1;
		} else {
			$order->status = 0;
		}
		
		$order->address = trim ( $kerwords [8 + $offset + $offsetadd] );
		
		// 处理成 （ 前面的部分
		
		// $ndis=stripos ( $order->add, "(" ,0);
		// $ndis2=stripos ( $order->add, "区",0 );
		// $ndislen=$ndis2-$ndis;
		
		// echo "</br>--###-";
		// echo $order->add;
		// echo $ndis." ".$ndis2." ".$ndis." ";
		
		// if($ndislen>0)
		// {
		// $order->district=substr($order->add,ndis+6,$ndislen+2);
		
		// }
		
		// echo "strlen";
		// echo $order->add ;
		
		$order->adddetail = trim ( $kerwords [8 + $offset + $offsetadd] . " " . $kerwords [9 + $offset + $offsetadd] );
	}
	function getSSUserinfo($rawData, &$order) 

	{
		$pos = stripos ( $rawData, "1" );
		
		$order->ssname = substr ( $rawData, 0, $pos );
		
		$order->ssmobile = substr ( $rawData, $pos, 11 );
	}
}